<template>
	<view class="edit-container">
		<!-- 头像选择 -->
		<view class="edit-item avatar-item">
			<text class="item-label">头像</text>
			<u--image
				:showLoading="true"
				:src="userInfo.avatar"
				width="50px"
				height="50px"
				@click="uploadImg"
			  ></u--image>
		</view>
		
		<!-- 用户名输入 -->
		<view class="edit-item">
			<text class="item-label">用户名</text>
			<input type="nickname" maxlength="16" placeholder="请输入用户名" v-model="userInfo.username"/>
		</view>
		
		<!-- 手机号输入 -->
		<view class="edit-item">
			<text class="item-label">手机号</text>
			<input placeholder="请输入手机号" v-model="userInfo.mobile"/>
		</view>
		
		<!-- 邮箱输入 -->
		<view class="edit-item">
			<text class="item-label">邮箱</text>
			<input placeholder="请输入邮箱" v-model="userInfo.email"/>
		</view>
		
		<!-- 性别选择 -->
		<view class="edit-item">
			<text class="item-label">性别</text>
			<u-radio-group 
			    v-model="gender"
				placement="row"
				@change="groupChange" customStyle="display:flex;">
				<u-radio label="男" name="1"></u-radio>
				<u-radio label="女" name="2"></u-radio>
			</u-radio-group>
		</view>
		
		<!-- 生日选择 -->
		<view class="edit-item">
			<text class="item-label">生日</text>
			<view class="birthday-select" @click="show = true">
				<text>{{formatDate(value1)}}</text>
				<u-icon name="arrow-right" color="#999" size="28"></u-icon>
			</view>
			<u-datetime-picker
				:show="show"
				v-model="value1"
				mode="date"
				:formatter="formatter"
				@confirm="dateConfirm"
				@cancel="dateCancel"
				:minDate="minDate"
				:maxDate="maxDate"
			></u-datetime-picker>
		</view>
		
		<!-- 保存按钮 -->
		<view class="save-btn">
			<u-button 
				type="primary"
				text="保存"
				@click="saveUserInfo"
			></u-button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			userInfo: {
				avatar: '',
				username: '',
				mobile: '',
				email: '',
				gender: 1,
				birthday: '',
				userId: 0
			},
			src: '',
			gender: "1",
			showDatePicker: false,
			show: false,
			value1: Number(new Date()),
			minDate: new Date('1900-01-01').getTime(),
			maxDate: new Date().getTime(),
			API: getApp().globalData().API
		}
	},
	onLoad() {
		this.getUserInfo()
	},
	methods: {
		// 获取用户信息
		getUserInfo() {
			let that = this
			uni.request({
				url: getApp().globalData().API + '/user/getUserInfo',
				data: {
					userId: that.userId
				},
				success(res) {
					that.userInfo = res.data.data
					that.gender = that.userInfo.gender.toString()
					that.value1 = that.userInfo.birthday
				}
			})
		},
		// 日期格式化函数
		formatter(type, value) {
			if (type === 'year') {
				return `${value}年`
			}
			if (type === 'month') {
				return `${value}月`
			}
			if (type === 'day') {
				return `${value}日`
			}
			return value
		},
		
		// 格式化显示日期
		formatDate(timestamp) {
			const date = new Date(timestamp)
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		},
		
		// 确认选择
		dateConfirm(e) {
			let that = this;
			this.value1 = e.value
			this.userInfo.birthday = this.formatDate(e.value)
			this.show = false
		},
		
		// 取消选择生日
		dateCancel() {
			this.show = false
		},
		groupChange(e){
			this.userInfo.gender = e
		},
		uploadImg(){
			let that = this;
			uni.chooseImage({
				success: (chooseImageRes) => {
					const tempFilePaths = chooseImageRes.tempFilePaths;
					const token = uni.getStorageSync('token');
					uni.uploadFile({
						url: that.API + '/uploadFile',
						filePath: tempFilePaths[0],
						name: 'file',
						header: {
							'token': token  // 添加token到请求头
						},
						formData: {
							'user': 'test'
						},
						success: (uploadFileRes) => {
							that.userInfo.avatar = uploadFileRes.data
						}
					});
				}
			});

		},
		saveUserInfo(){
            // 验证手机号格式
            if (this.userInfo.mobile!='' && !/^1[3-9]\d{9}$/.test(this.userInfo.mobile)) {
                uni.showToast({
                    title: '请输入正确的手机号',
                    icon: 'none'
                })
                return
            }
            
            // 验证邮箱格式
            if (this.userInfo.email != '' && !/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(this.userInfo.email)) {
                uni.showToast({
                    title: '请输入正确的邮箱格式',
                    icon: 'none'
                })
                return
            }
            
            // 验证通过，提交表单
            uni.showLoading({
                title: '保存中...'
            })
            uni.request({
                url: getApp().globalData().API + '/user/update',
                method: 'POST',
                data: this.userInfo,
                success: (res) => {
					console.log(res);
                    if (res.data.code === 200) {
                        uni.showToast({
                            title: '保存成功',
                            icon: 'success'
                        })
                        setTimeout(() => {
                            uni.navigateBack()
                        }, 1500)
                    } else {
                        uni.showToast({
                            title: res.data.msg || '保存失败',
                            icon: 'none'
                        })
                    }
                },
                fail: () => {
                    uni.showToast({
                        title: '保存失败，请重试',
                        icon: 'none'
                    })
                },
                complete: () => {
                    uni.hideLoading()
                }
            })
        }
	}
}
</script>

<style lang="scss">
.edit-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding: 20rpx;
	
	.edit-item {
		background-color: #fff;
		padding: 30rpx;
		margin-bottom: 20rpx;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		
		.item-label {
			width: 140rpx;
			font-size: 28rpx;
			color: #333;
		}
		
		.item-input {
			flex: 1;
			font-size: 28rpx;
		}
		
		.item-content {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
		
		.birthday-select {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 28rpx;
			color: #333;
		}
	}
	
	.avatar-item {
		cursor: pointer;
	}
	
	.save-btn {
		margin-top: 60rpx;
		padding: 0 30rpx;
	}
}
</style>
